package com.lkm.app_ui.ui;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.lkm.app_ui.AppConst;
import com.lkm.app_ui.MBaseFragment;
import com.lkm.app_ui.MyApplication;
import com.lkm.app_ui.R;
import com.lkm.app_ui.RouterUINavigation;
import com.lkm.app_ui.RunTimeData;
import com.lkm.app_ui.help.AppUIHelp;
import com.lkm.app_ui.help.QRCodeUtil;
import com.lkm.app_ui.m.Imple.fun.PayCodeTask;
import com.lkm.app_ui.m.fun.DelegatePayTask;
import com.lkm.app_ui.m.fun.FunItem;
import com.lkm.app_ui.m.fun.FunModule;
import com.lkm.app_ui.m.input.OnInputContentEvent;
import com.lkm.app_ui.m.vip.OnVipEvent;
import com.lkm.app_ui.m.vip.VipInfo;
import com.lkm.app_ui.m.vip.VipModule;
import com.lkm.app_ui.view.choiceCard.ChoiceCard;
import com.lkm.app_ui.view.choiceCard.ChoiceItem;
import com.lkm.app_ui.view.choiceCard.IChoiceItem;
import com.lkm.comlib.fun_m.NetworkStateModule;
import com.lkm.comlib.help.ImageViewLoadHelp;
import com.lkm.comlib.help.ViewHelp;
import com.lkm.comlib.ui.BaseFragmentActivity;
import com.lkm.frame.P;
import com.lkm.frame.otto.LinkBus;
import com.lkm.frame.otto.LinkBusCycleWrapper;
import com.lkm.frame.otto.Observer;
import com.lkm.frame.otto.ObserverAutoNext;
import com.lkm.frame.task.ProgressData;
import com.lkm.frame.task2.BackCallAdapter;
import com.lkm.frame.task2.Task;
import com.lkm.frame.task2.TaskCollection;
import com.lkm.frame.task2.TaskCollectionCycle;
import com.lkm.frame.util.CycleHelp;
import com.lkm.javatool.NumberHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.market2_0.entity.ResponEntity;
import com.lkm.market2_0.help.SteelardHelp;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyardserver.OnSteelyardKeyEvent;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;

import static com.lkm.app_ui.m.fun.DelegatePayTask.*;


public class PayFragment extends MBaseFragment implements ChoiceCard.ChoiceCardBC {

    public static PayFragment lastPayFragment;

    public static PayFragment getInstance(@DelegatePayTask.PayType int payType) {
        PayFragment f    = lastPayFragment = new PayFragment();
        Bundle      data = new Bundle();
        data.putInt("payType:i", payType);
        f.setArguments(data);
        return f;
    }

    @DelegatePayTask.PayType
    private int payType = 0;

    @Override
    protected int configLayoutResID() {
        return R.layout.fragment_pay;
    }

    private ImageViewLoadHelp payImageViewLoadHelp;

    private FunModule      funModule;
    private TaskCollection taskCollection;

    private OrderEntity orderEntity;

    private TextView tv_tips, tv_delegate;

    private ChoiceCard mChoiceCard;

    private static final int Money_keyCode       = 0;//现金支付
    private static final int WVip_keyCode        = 1;//微会员支付
    private static final int Delegate_keyCode    = 2;//聚合支付
    private static final int Vip_keyCode         = 3;//会员支付
    private static final int VipMoney_keyCode    = 4;//会员卡与现金支付
    private static final int VipDelegate_keyCode = 5;//会员卡与聚合支付


    private static final int vipOrScanPay_keyCode = 6;//进入会员刷卡模式


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        RunTimeData.lastPayOKvipInfo = null;
        payType = getArguments().getInt("payType:i");

        funModule = MyApplication.getInstance().getModuleManager().loadModule(FunModule.class);
        taskCollection = new TaskCollectionCycle(MyApplication.getInstance().getTaskManager2(), holdCycleHelp());


        orderEntity = RunTimeData.orderEntity;

        tv_delegate = findViewById(R.id.tv_delegate);
        tv_tips = findViewById(R.id.tv_tips);
//        ((TextView) findViewById(R.id.tv_totalPrice)).setText("应付：" + SteelardHelp.formatMoney(orderEntity.totalPrice) + "元");

        if (!RunTimeData.steelyardExtData.payOnlineInfo.isDelegatePay && !RunTimeData.steelyardExtData.payOnlineInfo.isVipCardPay) {
            //P.p("Bill-> PayFragment -> No_isDelegatePay and No_isVipCardPay");
            RouterUINavigation.getInstance().showPayOutline((BaseFragmentActivity) getActivity());
            RouterUINavigation.getInstance().dismiss(this);

            return;
        }


//        RunTimeData.steelyardExtData.payOnlineInfo.isUsbVipSystem = true;
//        RunTimeData.steelyardExtData.payOnlineInfo.isDelegatePay = true;
//        RunTimeData.steelyardExtData.payOnlineInfo.isVipCardPay = true;


        mChoiceCard = findViewById(R.id.ChoiceCard);
        mChoiceCard.setItemViewHeigth(ViewHelp.getPX(getActivity(), R.dimen.dp100px));
        mChoiceCard.init(false, R.layout.view_choice_card, R.layout.item_fun_p, R.layout.item_fun, 1);

        mChoiceCard.setChoiceCardBC(this);
        switch (payType) {
            case PayType_WVip:
                RunTimeData.orderEntity.payTypeName = "微会员支付";
                break;
            case PayType_Vip:
                RunTimeData.orderEntity.payTypeName = "会员支付";
                break;
            case PayType_Delegate:
                RunTimeData.orderEntity.payTypeName = "聚合支付";
                break;
            case PayType_Money:
                RunTimeData.orderEntity.payTypeName = "现金支付";
                break;
        }
        if (payType == PayType_Vip) {
            delegatePayTask();
        } else {
            delegatePayTask();
        }


        if (RunTimeData.steelyardExtData.payOnlineInfo.isUsbVipSystem) {
            ViewGroup vip_content = ((ViewGroup) findViewById(R.id.vip_content));
            vipView = new VipView(vip_content);
//            vip_content.addView(new VipView(vip_content).getView());
        }


        reOnKeyEvent();
        onInputContentEvent();

        if (RunTimeData.isSongjian) {
            //P.p("Bill-> PayFragment ->isSongjian");
            RouterUINavigation.getInstance().showPayOutline((BaseFragmentActivity) getActivity());
            RouterUINavigation.getInstance().dismiss(this);
        }


        initDatax();
    }

    private void initDatax() {
        List<FunItem> funItems = new ArrayList<>();
        funItems.add(new FunItem("" + Money_keyCode, Money_keyCode + "：现金支付", payType == PayType_Money));

        if (RunTimeData.steelyardExtData.payOnlineInfo.isVipW)
            funItems.add(new FunItem("" + WVip_keyCode, WVip_keyCode + "：微会员支付", payType == PayType_WVip));

        if (RunTimeData.steelyardExtData.payOnlineInfo.isDelegatePay)
            funItems.add(new FunItem("" + Delegate_keyCode, Delegate_keyCode + "：聚合支付", payType == PayType_Delegate));


        if (RunTimeData.steelyardExtData.payOnlineInfo.isVipCardPay) {
            funItems.add(new FunItem("" + Vip_keyCode, Vip_keyCode + "：会员支付", payType == PayType_Vip));

            funItems.add(new FunItem("" + VipMoney_keyCode, VipMoney_keyCode + "：会员卡与现金支付", payType == PayType_Vip));

            if (RunTimeData.steelyardExtData.payOnlineInfo.isDelegatePay)
                funItems.add(new FunItem("" + VipDelegate_keyCode, VipDelegate_keyCode + "：会员卡与聚合支付", payType == PayType_Vip));


        }

        funItems.add(new FunItem("" + vipOrScanPay_keyCode, vipOrScanPay_keyCode + "：进入会员刷卡模式", false));


        if (curVipInfo != null)
            funItems.add(new FunItem("8", "8：登出会员"));
        funItems.add(new FunItem("9", "9：退出"));

        ChoiceItem[] cis = new ChoiceItem[funItems.size()];
        int          i   = 0;
        for (FunItem funItem : funItems) {
            cis[i] = new ChoiceItem(funItem.id, funItem.name);
            cis[i].setTag(funItem);
            cis[i].setIsChoice(funItem.isChoice);
            i++;
        }

        mChoiceCard.binData(cis);


    }

    private void playpayType() {
        if (payType == PayType_Vip)
            PlayBeepEvent.send(PlayBeepEvent.TYPE_pleaseCard);
        else if (payType == PayType_WVip || payType == PayType_Delegate)
            PlayBeepEvent.send(PlayBeepEvent.TYPE_pleaseScanQr);
    }

    @Override
    public void onChoiceChangeListener(ChoiceCard cc, IChoiceItem c, int index) {
        if (c.getIsChoice()) {
            FunItem funItem = (FunItem) c.getTag();
            float   number  = -1;
            try {
                number = Float.parseFloat(funItem.id);
            } catch (Exception e) {
                e.printStackTrace();
            }
            handNumber(number, true);
        }

    }

    private void handNumber(float number, boolean isFinally) {

        int num = (int) number;

        if (num == OnSteelyardKeyEvent.KEYCODE_Money) {
            num = Money_keyCode;
        } else if (num == OnSteelyardKeyEvent.KEYCODE_PAY) {

            num = Money_keyCode;
        } else if (num == OnSteelyardKeyEvent.KEYCODE_VipCard) {
            num = Vip_keyCode;
        } else if (num == OnSteelyardKeyEvent.KEYCODE_VipW) {
            num = WVip_keyCode;
        } else if (num == OnSteelyardKeyEvent.KEYCODE_DelegatePay) {
            num = Delegate_keyCode;
        } else if (num == vipOrScanPay_keyCode) {

            initDatax();

            if (vipView != null) vipView.reView();
            return;
        }

        boolean hasItemFun = false;

        IChoiceItem[] items = mChoiceCard.getData();
        for (IChoiceItem item : items) {
            FunItem funItem = (FunItem) item.getTag();
            if (NumberHelp.toInt(funItem.id, -1) == num) {
                hasItemFun = true;
                break;
            }
        }
        if (!hasItemFun) return;


        switch (num) {
            case Money_keyCode:
                RunTimeData.orderEntity.payTypeName = "现金支付";

//                RouterUINavigation.getInstance().showPayOutline((BaseFragmentActivity) getActivity());
//                RouterUINavigation.getInstance().dismiss(this);
                payType = PayType_Money;
                delegatePayTask();
                break;
            case Vip_keyCode:
                RunTimeData.orderEntity.payTypeName = "会员支付";
                payType = PayType_Vip;
                delegatePayTask();
                break;
            case Delegate_keyCode:
                RunTimeData.orderEntity.payTypeName = "聚合支付";
                payType = PayType_Delegate;
                delegatePayTask();
                break;
            case WVip_keyCode:
                RunTimeData.orderEntity.payTypeName = "微会员支付";
                payType = PayType_WVip;
                delegatePayTask();
                break;


            case 5:

                delegatePayTask();
                break;
            case 8:
                if (curVipInfo != null) {
                    VipModule vipModule = AppConst.getModuleManager().peekModule(VipModule.class);
                    if (vipModule != null)
                        vipModule.exitVip();
                }
                break;
            case 9:
                RunTimeData.orderEntity.payTypeName = "";
                RouterUINavigation.getInstance().dismiss(this);
                break;

        }


    }

    private void reOnKeyEvent() {
        LinkBusCycleWrapper.register(new ObserverAutoNext<OnSteelyardKeyEvent>() {
            @Override
            public Class<OnSteelyardKeyEvent> getBusEventClass() {
                return OnSteelyardKeyEvent.class;
            }

            @Override
            public void onReceiver(OnSteelyardKeyEvent data) {
                if (!data.isIntercepted()) {
                    data.setIntercepted(true);
                    if (data.getKeyCode() == OnSteelyardKeyEvent.KEYCODE_FUN) {
                        RouterUINavigation.getInstance().dismiss(PayFragment.this);
                    }

                    handNumber(data.getKeyCode(), false);
                }
            }
        }, holdCycleHelp(), CycleHelp.CycleType.Destroy);
    }

    private Observer onInputContent = null;

    private void onInputContentEvent() {

        LinkBus.registerReceiver(0, onInputContent = new Observer<OnInputContentEvent>() {

            @Override
            public void onReceiver(OnInputContentEvent data, Runnable nextRun) {
                initDatax();

                AppUIHelp.tryShowTipsLong("扫码支付中");
                PayCodeTask payCodeTask = new PayCodeTask();
                payCodeTask.action();
                VipInfo vipInfo = null;
                try {
                    vipInfo = AppConst.getModuleManager().peekModule(VipModule.class).curVipInfo();
                } catch (Exception e) {
                }

                payCodeTask.setParam(new DelegatePayTask.DelegatePayTaskP(data.getContent(), orderEntity, DelegatePayTask.PayType_PayCode, vipInfo));
                payCodeTask.addBackCall(new BackCallAdapter<Void, ResponEntity<Void>>() {
                    @Override
                    protected void onEnd(Task<?, Void, ResponEntity<Void>> task, ResponEntity<Void> re, boolean isCancel) {
                        super.onEnd(task, re, isCancel);
                        if (re == null || !re.isSuccess()) {
                            String tips = re == null ? null : re.getMsg();
                            if (StringHelp.isEmpty(tips))
                                tips = "支付码解析失败" + (NetworkStateModule.getInstance().getIsNetworkOK() ? "" : "，当前无网络");
                            AppUIHelp.tryShowTipsSHORT(tips);
                        }
                    }


                });
                taskCollection.add(payCodeTask.execTask());


            }

            @Override
            public Class getBusEventClass() {
                return OnInputContentEvent.class;
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (onInputContent != null) {
            LinkBus.unregisterReceiver(onInputContent);
            onInputContent = null;
        }
    }


    private void delegatePayTask() {
        showPayContent(null);

        if (payType == PayType_Vip && curVipInfo == null) {
            tv_tips.setText("请刷会员卡");

            initDatax();
            playpayType();
            return;
        }

        payImageViewLoadHelp = new ImageViewLoadHelp(getActivity(), Math.max(getResources().getDisplayMetrics().heightPixels, getResources().getDisplayMetrics().widthPixels), holdCycleHelp());
        payImageViewLoadHelp.setHasImagScaleType(ImageView.ScaleType.CENTER_INSIDE);
        payImageViewLoadHelp.setLoadingImagScaleType(ImageView.ScaleType.CENTER_INSIDE);
        payImageViewLoadHelp.setNotImagScaleType(ImageView.ScaleType.CENTER_INSIDE);

        DelegatePayTask delegatePayTask = funModule.delegatePay(orderEntity, "", payType);
        delegatePayTask.addBackCall(delegatePayTaskBC);
        taskCollection.add(delegatePayTask.getSerialNum());
    }


    private boolean                                                     isShowReloadDelegatePayTask = false;
    private BackCallAdapter<DelegatePayTask.DelegatePayTaskPR, Boolean> delegatePayTaskBC           = new BackCallAdapter<DelegatePayTask.DelegatePayTaskPR, Boolean>() {
        @Override
        public void onPreExecute(Task<?, DelegatePayTask.DelegatePayTaskPR, Boolean> task) {
            super.onPreExecute(task);

            isShowReloadDelegatePayTask = false;
//            findViewById(R.id.tv_pay_reload).setVisibility(View.GONE);
            tv_tips.setText("加载支付信息..");
//            ViewUIHelp.showProgressBar(getActivity(),"加载支付信息..","delegatePayTask");
        }

        @Override
        protected void onEnd(Task<?, DelegatePayTask.DelegatePayTaskPR, Boolean> task, Boolean aBoolean, boolean isCancel) {
            super.onEnd(task, aBoolean, isCancel);

        }

        @Override
        public void onProgresing(Task<?, DelegatePayTask.DelegatePayTaskPR, Boolean> task, ProgressData<DelegatePayTask.DelegatePayTaskPR> progressData) {
            super.onProgresing(task, progressData);

            initDatax();

            String allp = SteelardHelp.formatMoney(orderEntity.totalPrice);
            String yf   = orderEntity.payment_amount;

            TextView tv_tipsPrice = findViewById(R.id.tv_tipsPrice);
            if (StringHelp.isEmpty(yf)) {
                tv_tipsPrice.setVisibility(View.GONE);
                ((TextView) findViewById(R.id.tv_totalPrice)).setText("应付：" + allp + "元");
            } else {
                ((TextView) findViewById(R.id.tv_totalPrice)).setText("应付：" + yf + "元");
                tv_tipsPrice.setVisibility(View.VISIBLE);
                tv_tipsPrice.setText("总价:" + allp + "元");
            }

            if (progressData.getData().step == DelegatePayTask.DelegatePayTaskPR.step_requestFail) {

                tv_tips.setText(StringHelp.isEmpty(progressData.getData().msg) ? "加载支付信息失败" : progressData.getData().msg);
//                findViewById(R.id.tv_pay_reload).setVisibility(View.VISIBLE);
                isShowReloadDelegatePayTask = true;

            }
            if (progressData.getData().step == DelegatePayTask.DelegatePayTaskPR.step_content) {
                playpayType();
                showPayContent(progressData.getData());
            } else if (progressData.getData().step == DelegatePayTask.DelegatePayTaskPR.step_paySuccess) {


//                funModule.exitScene(FunModule.SCENE_shopping);

                RunTimeData.lastPayOKvipInfo = curVipInfo;
                RouterUINavigation.getInstance().dismiss(PayFragment.this);
            } else if (progressData.getData().step == DelegatePayTask.DelegatePayTaskPR.step_payFail) {


//                funModule.exitScene(FunModule.SCENE_shopping);
                RouterUINavigation.getInstance().dismiss(PayFragment.this);
            }

        }
    };

    private void showPayContent(DelegatePayTask.DelegatePayTaskPR content) {
        if (content == null) {
            tv_delegate.setText("");
            findViewById(R.id.img_qr).setVisibility(View.INVISIBLE);
            return;
        }
        tv_delegate.setText(content.msg);
        tv_tips.setText("");

        if (content.type == 1) {

//                    findViewById(R.id.view_delegate).setVisibility(View.VISIBLE);
//                    findViewById(R.id.img_qr).setVisibility(View.GONE);
//                    ((MWebView) findViewById(R.id.view_delegate)).loadUrl(progressData.getData().url);

            findViewById(R.id.img_qr).setVisibility(View.VISIBLE);
            ((ImageView) findViewById(R.id.img_qr)).setImageBitmap(QRCodeUtil.createImage(content.url, 200, 200));
        } else {

//                    findViewById(R.id.view_delegate).setVisibility(View.GONE);
            findViewById(R.id.img_qr).setVisibility(View.VISIBLE);
            payImageViewLoadHelp.setImage(((ImageView) findViewById(R.id.img_qr)), content.url);
        }
//                ((TextView) findViewById(R.id.tv_delegate)).setText(progressData.getData().title);
    }


    @Override
    protected boolean configIsLockKey() {
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 真正退出，而不是有别人来接替// 22-05-18 三厚哥说得不要清除。只有支付成功在提示页面退出再清除见com.lkm.app_ui.ui.VipOrderFixFragment.onDestroy

        if (lastPayFragment == this) {
            VipModule vipModule = AppConst.getModuleManager().peekModule(VipModule.class);
            if (vipModule != null)
                vipModule.exitVip();
        }
    }


//            FunModule steelyardServerModule = AppConst.getModuleManager().loadModule(FunModule.class);


//            FunModule steelyardServerModule = AppConst.getModuleManager().loadModule(FunModule.class);


    private VipView vipView;

    private VipInfo curVipInfo = null;

    private class VipView {

        private View view;

        public void reView() {
            if (curVipInfo == null) {

                ((TextView) view.findViewById(R.id.tv_vip_name)).setText(String.format("请按‘%s’，进入会员刷卡模式，进行会员刷卡", vipOrScanPay_keyCode));
            } else {

                ((TextView) view.findViewById(R.id.tv_vip_name)).setText(

                        "会员号：" + curVipInfo.getVipNo() + "\n" +
                                "余额：" + curVipInfo.getAmount()
                );
            }
        }

        public VipView(ViewGroup group) {
            view = ViewHelp.inflate(getActivity(), R.layout.view_pay_vip, group);

            LinkBusCycleWrapper.register(new ObserverAutoNext<OnVipEvent>() {
                @Override
                public void onReceiver(OnVipEvent data) {
                    VipInfo oldVipInfo = curVipInfo;
                    VipInfo vipInfo    = data.getVipInfo();
                    curVipInfo = vipInfo;
                    reView();
                    if (curVipInfo != null) {
                        initDatax();

                        data.setIntercepted(true);
                    }

                    String oldVipNo = oldVipInfo == null ? "" : oldVipInfo.getVipNo();
                    String curVipNo = curVipInfo == null ? "" : curVipInfo.getVipNo();

                    if (!StringHelp.equals(oldVipNo, curVipNo)) {
                        delegatePayTask();
                    }

                    initDatax();

                }

                @Override
                public Class<OnVipEvent> getBusEventClass() {
                    return OnVipEvent.class;
                }
            }, holdCycleHelp(), CycleHelp.CycleType.Destroy);

        }

        public View getView() {
            return view;
        }
    }
}
